<?php
/*
功能：数据缓存类
*/
class cpCache
{
	public $config = array();

    public function __construct($config=array())
    {
		$this->config['DATA_CACHE_PATH'] = isset($config['DATA_CACHE_PATH'])?$config['DATA_CACHE_PATH']:'./data/cache';	//缓存目录
        $this->config['DATA_CACHE_TIME'] = isset($config['DATA_CACHE_TIME'])?$config['DATA_CACHE_TIME']:0;//缓存时间
		$this->config['DATA_CACHE_CHECK']=isset($config['DATA_CACHE_CHECK'])?$config['DATA_CACHE_CHECK']:false;//是否验证数据
		$this->config['DATA_CACHE_COMPRESS']=isset($config['DATA_CACHE_COMPRESS'])?$config['DATA_CACHE_COMPRESS']:false;//是否压缩数据
		$this->config['DATA_CACHE_PREFIX']=isset($config['DATA_CACHE_PREFIX'])?$config['DATA_CACHE_PREFIX']:'';//前缀
		
        if(substr($this->config['DATA_CACHE_PATH'], -1) != "/")    
		{
			$this->config['DATA_CACHE_PATH'] .= "/";
		}
		
        if($this->checkDir()==false)//检查缓存目录
		{
			$this->error($this->config['DATA_CACHE_PATH']." 缓存目录不存在");
		}

    }
	
/*
检查缓存目录
*/
	 private function checkDir()
    {
        // 如果缓存目录不存在或者不是目录，则创建缓存目录
        if((!file_exists($this->config['DATA_CACHE_PATH']))||(!is_dir($this->config['DATA_CACHE_PATH']))) 
		{
           //创建缓存目录
		    if (!@mkdir($this->config['DATA_CACHE_PATH'],0777))
             {
			    return false;
			 }
             
        }
		//检查缓存目录是否可写，不可写则修改它的属性
		else if(!is_writable($this->config['DATA_CACHE_PATH']))
		{
			return	chmod($this->config['DATA_CACHE_PATH'],0777);
		}
		else
		{	
			return true;
		}
    }
	 
	  private function getFilename($name)
    {
        $name=md5($name);
        $filename=$this->config['DATA_CACHE_PREFIX'].$name.'.php';
        return $this->config['DATA_CACHE_PATH'].$filename;
    }
	/*
	读取缓存
	*/
    public function get($name,$cache_prefix='')
    {
		if(!empty($cache_prefix))
		{
			$this->config['DATA_CACHE_PREFIX']=$cache_prefix;
		}
        $filename   =   $this->getFilename($name);//获取缓存文件名
        if (!file_exists($filename)|| !is_file($filename)) 
		{
           return false;
        }

        $content    =   file_get_contents($filename);
        if( false !== $content) 
		{
            $expire  =  (int)substr($content,8, 12);
            if($expire != -1 && time() > filemtime($filename) + $expire) 
			{
                //缓存过期删除缓存文件
                unlink($filename);
                return false;
            }
            if($this->config['DATA_CACHE_CHECK']) 
			{
				//开启数据校验
                $check  =  substr($content,20, 32);
                $content   =  substr($content,52, -3);
                if($check != md5($content)) 
				{
					//校验错误
                    return false;
                }
            }
			else 
			{
            	$content   =  substr($content,20, -3);
            }
			
            if($this->config['DATA_CACHE_COMPRESS'] && function_exists('gzcompress')) 
			{
                //启用数据压缩
                $content   =   gzuncompress($content);
            }
            $content    =   unserialize($content);//解序列化数据
            return $content;
        }
        else 
		{
            return false;
        }
    }

	/*
	写入缓存
	
	参数：string $name 缓存变量名
		  mixed $value  存储数据
		 $expire  有效时间 -1 为永久
	返回布尔值
	*/
    public function set($name,$value,$expire=NULL,$cache_prefix='')
    {
        if($expire==NULL)
		{
            $expire =  $this->config['DATA_CACHE_TIME'];
        }
		if(!empty($cache_prefix))
		{
			$this->config['DATA_CACHE_PREFIX']=$cache_prefix;
		}
		//缓存时间为0,则不缓存
		if(empty($expire))
		{
			return false;
		}
		
        $filename   =   $this->getFilename($name);//获取文件名
        $data   =   serialize($value);//将数据序列化
		
        if( $this->config['DATA_CACHE_COMPRESS'] && function_exists('gzcompress')) 
		{
            //数据压缩
            $data   =   gzcompress($data,3);
        }
        if($this->config['DATA_CACHE_CHECK']) 
		{
			//开启数据校验
            $check  =  md5($data);
        }
		else 
		{
            $check  = '';
        }
        $data    = "<?php\n//".sprintf('%012d',$expire).$check.$data."\n?>";
		
        $result  =   file_put_contents($filename,$data);
        if($result) 
		{
            clearstatcache();//清除文件状态缓存
            return true;
        }
		else 
		{
            return false;
        }
    }

	/*
	删除缓存
	*/
    public function del($name)
    {
        return unlink($this->getFilename($name));
    }
	
	/*
	清除缓存
	*/
    public function clear()
    {
        $path   =  $this->config['DATA_CACHE_PATH'];
        if ( $dir = opendir( $path ) )
        {
            while ( $file = readdir( $dir ) )
            {
                $check = is_dir( $file );
                if ( !$check )
                    unlink( $path . $file );
            }
            closedir( $dir );
            return true;
        }
    }
	    //输出错误信息
	public function error($str)
	{
		require_once(dirname(__FILE__).'/cpError.class.php');
		cpError::show($str);
	}
}
?>
